/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.util;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author jasuke
 */
public class Utils implements Serializable {

    public static final String MONEY_PATERN = "#,##0.####";
    public static final String PERCENT_PATERN = "#.00#";
    public static final BigDecimal MAX_BIGDECIMAL = BigDecimal.valueOf(9999999999999999.9999);
    public static final BigDecimal MAX_PERCENTAGE = BigDecimal.valueOf(999.99);
    public static final String SQLDATE_PATERN = "YYYY-MM-DD";
    
            
    public Utils() {
    }
    
    public static String formatDate(Date date) {
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
	return dateFormat.format(date);
    }
    
    public static BigDecimal parseNumberToBigDecimal(String text){
       // if(!StringUtils.hasText(text)) return BigDecimal.ZERO;
        try {
            BigDecimal number = new BigDecimal(NumberFormat.getInstance().parse(text).doubleValue());
            return number;
        } catch (ParseException ex) {
        
        }
        return null;
    }
    
    public static String getValueFromTextNumber(String text) {
        final char txt[] = text.toCharArray();
        StringBuilder sb = new StringBuilder();
        String tmp;
        for (int i=0; i<txt.length; i++) {
            tmp = String.valueOf(txt[i]);

            if (tmp.equals(".") || tmp.equals(",")) {
            } else {
                sb.append(tmp);
            }
        }

        return sb.toString();
    }
    
    public static String formatNumber(BigDecimal value) {
        NumberFormat numberFormatter= NumberFormat.getInstance();

        String formatOut=numberFormatter.format(value);
        
        return formatOut;
    }

    public static String getClientIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	} 
    
    public static String getClienyIpAddress() {
               
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext ext = context.getExternalContext();
        HttpServletRequest request = (HttpServletRequest)ext.getRequest();
        String ipAddress = src.util.Utils.getClientIpAddr(request);
        return ipAddress;
    }
    
    public static SelectItem selectItemIndexOfValue(List<SelectItem> list, Object value) {
        
        if(value == 0) {
            value=null;
        }
        
        SelectItem selectItem = null;
        if (value!=null) {
            int i=0;
            boolean found=false;
            while (i<list.size() && !found) {
                selectItem = list.get(i);
                found = value.equals(selectItem.getValue()) ? true:false;
                i++;
            }
        }
        
        return selectItem;
    }
    
    public static Object selectItemValueOf(List<SelectItem> list, Object value) {
        SelectItem selectItem = Utils.selectItemIndexOfValue(list, value);
        if (selectItem!=null) return selectItem.getLabel();
        else return null;
    }
    
    public static String fmtSQLString(String value) {
        return "\'"+value+"\'";
    }
	
    public static String fmtSQLDate(java.util.Date value) {
        return "date\'"+value+"\'";
    }
    
    public static BigDecimal moneyRounder(BigDecimal value) {
	MathContext mc = new MathContext(0);
        BigDecimal rounder = BigDecimal.valueOf(50);
        
        BigDecimal hasil;
        BigDecimal remaind, div;
        remaind = value.remainder(rounder, mc);
        div = value.divide(rounder, 0, RoundingMode.HALF_DOWN);
                
        if(remaind.compareTo(BigDecimal.valueOf(0)) > 0) 
            hasil= rounder.multiply(div).add(rounder);
        else hasil= value;    
       
        return hasil;
    }
        
    public static Date setMoth(Date date, int monthIdx) {
        
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, monthIdx);
        
        return cal.getTime();
    } 
    
    public static int getDayOftheMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    } 
 
    public static List<SelectItem> getMonths() {
    
        List<SelectItem> rn = new ArrayList<>();
        String[] months = new DateFormatSymbols().getMonths();
        for (int i = 0; i < months.length; i++) {
            rn.add(new SelectItem(i+1, months[i]));
        }
        return rn;
    }
    
    public static String getMonthName(int idx) {
        String[] months = new DateFormatSymbols().getMonths();
        return months[idx];
    }
    
    public static String logActions(String userName, Date date) {
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
	return userName+"_"+dateFormat.format(date);
        
    }
    
    public static String terbilang(String angka) {
        int length = angka.length();
        if (length <= 6) {
        String[] bil = new String[]
        {"","Satu","Dua","Tiga","Empat","Lima",

        "Enam","Tujuh","Delapan","Sembilan","Sepuluh","Sebelas"};

        int x = Integer.valueOf(angka);

        if (x <= 0) {return "";}
        else if (x < 12) {
            return bil[(int)x] + " ";
        } else if (x < 20) {
            return terbilang(String.valueOf(x-10)) + "Belas ";
        } else if (x < 100) {
            return terbilang(String.valueOf(x/10)) + "Puluh " +  terbilang(String.valueOf(x%10));
        } else if (x < 200) {
            return "Seratus " + terbilang(String.valueOf(x-100));
        } else if (x < 1000) {
            return terbilang(String.valueOf(x/100)) + "Ratus " + terbilang(String.valueOf(x%100));
        } else if (x < 2000) {
            return "Seribu " + terbilang(String.valueOf(x-1000));
        } else {
            return terbilang(String.valueOf(x/1000)) + "Ribu " +  terbilang(String.valueOf(x%1000));
        }
        } else {
            int m = length % 3;
            if (m == 0) {m = 3;}
            String s1 = angka.substring(0,m);
            String s2 = angka.substring(m,length);

            String[] bil = new String[]{"","Juta","Milyar","Trilyun","Kuadriliun", "Kuintiliun","Heksiliun"};
            int index = 0;

            if (length <= 9) {index = 1;}
            else if (length <= 12) {index = 2;}
            else if (length <= 15) {index = 3;}
            else if (length <= 18) {index = 4;}
            else if (length <= 21) {index = 5;}
            else if (length <= 24) {index = 6;}
            else {return "zzzzz... capek hitungnya";}

            if (Integer.valueOf(s1) <= 0) {
                return terbilang(s2);
            } else {
                return terbilang(s1) + bil[index] + " " + terbilang(s2);
            }
          }
        }     
    
    public static String terbilangDecimal(BigDecimal value){
        /*double decimal = subtotal - (int)subtotal;
            int angka = (int)(subtotal);//(int)(Math.round(subtotal));// Double.toString(invoice.getTotalInvoice());
            String decimalTerbilang ="";
            if ((decimal*100) >0 ){
               int angkaDecimal  = (int)(decimal * 100);     
               decimalTerbilang =  String.valueOf(angkaDecimal).concat("/100 ");//.concat(invoice.getCurrency().getCurrency_name());
            }   */
        BigDecimal nilai = value.setScale(2, RoundingMode.UP);
        String rs="";
        //Character simbol = new Character(DecimalFormatSymbols.getInstance().getDecimalSeparator());
        Character simbol = new Character('.');
        if (String.valueOf(nilai).indexOf(simbol.toString())>0){
            BigDecimal decimal = nilai.subtract(new BigDecimal(nilai.intValue()));
            if (decimal.multiply(new BigDecimal(100)).compareTo(new BigDecimal(BigInteger.ZERO))>0){
                int angkaDecimal  = (decimal.multiply(new BigDecimal(100))).intValue();    
                
                rs = Utils.terbilang(String.valueOf(nilai.intValue())).concat("Koma ").concat(Utils.terbilang(String.valueOf(angkaDecimal)));
            }
            else rs = terbilang(String.valueOf(nilai.intValue()));
        }
        else {
            rs = Utils.terbilang(nilai.toString());
        }
        
        
        return rs;
    }
    
    public static String IntToStrFixed(int minLen, int value) {
        String tmpString = String.valueOf(value);
        for (int i=1; 1<minLen - tmpString.length(); i++) {
            tmpString = "0"+tmpString;
        }
        
        return tmpString; 
    }
     
    public static String formatSqlDate(Date date){
        return "to_date('".concat(new SimpleDateFormat("yyyy-MM-dd").format(date)).concat("','").concat(SQLDATE_PATERN).concat("')");
    }
    
 
    //chan buat ambil session aktif
    public static HttpSession getSession(){
        FacesContext fc = FacesContext.getCurrentInstance();
        return (HttpSession) fc.getExternalContext().getSession(false);
    }
    
    
     public static String captionPeriode(Date date1, Date date2){
        String hasil;
  
        hasil = "Periode Global";
        if ((date1 != null) && (date2 !=null)){
            hasil = "Periode "+formatDate(date1) + " s/d "+formatDate(date2);
        }
        else if ((date1 != null) && (date2 ==null)) {        
            hasil = "Per Tanggal "+ formatDate(date1);
        }
        /*if op1 = soEquals then
          hasil := 'Per Tanggal '+ formatDate(date1)
        else if (op1 = soGreaterThanEqualsTo) or (op1 = soGreaterThan) then
          hasil := 'Periode Dari '+ formatDate(date1)+' Sampai Sekarang'
        else if (op1 = soLessThanEqualsTo) or (op1=soLessThan) then
          hasil := 'Periode Awal s/d '+ formatDate(date1);
          * 
          */
     
        return hasil;
     }
 
    public static String fillString(char fillChar, int count){  
       char[] chars = new char[count];  
       java.util.Arrays.fill(chars, fillChar);  
       return new String(chars);  
    }  
    
    public String fixWidth(String string, int len, int alignment) {
        int mustAdd = len - string.length();
        String result = null;
        if (mustAdd > 0) {
            switch (alignment) {
                case Constanta.taLeftJustify : result = string.concat(fillString(' ', mustAdd));break;
                case Constanta.taRightJustify: result = fillString(' ', mustAdd).concat(string);break;
                case Constanta.taCenter: result = fillString(' ', mustAdd >> 1).concat(string).concat(fillString(' ', mustAdd >> 1));break;
            }
        } else if (mustAdd < 0) result = string;
        
        return result;
    };
    
}
